/**
 * @file ResourceManagement.vue
 * @description 教学资源管理主页面
 * @created 2024-06-25
 */

<template>
  <div class="resource-management">
      <div class="page-header">
      <h2>教学资源管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon>上传资源
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区 -->
    <div class="search-filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="资源名称">
          <el-input v-model="searchForm.name" placeholder="请输入资源名称" clearable />
        </el-form-item>
        <el-form-item label="资源类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 资源列表表格 -->
    <el-card class="resource-table-container">
      <el-table
        v-loading="loading"
        :data="resourceList"
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="resource_id" label="ID" width="80" sortable />
        <el-table-column prop="resource_name" label="资源名称" min-width="150">
          <template #default="scope">
            <el-tooltip :content="scope.row.description" placement="top" :show-after="500">
              <span class="resource-name">{{ scope.row.resource_name }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="resource_type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.resource_type)">
              {{ scope.row.resource_type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category_name" label="分类" width="120" />
        <el-table-column prop="file_size" label="大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="download_count" label="下载次数" width="100" sortable />
        <el-table-column prop="audit_status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.audit_status)">
              {{ getStatusText(scope.row.audit_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" sortable />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" link @click="handlePreview(scope.row)">
              <el-icon><View /></el-icon>预览
            </el-button>
            <el-button type="primary" link @click="handleDownload(scope.row)">
              <el-icon><Download /></el-icon>下载
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传资源对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传资源"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="resourceName">
          <el-input v-model="uploadForm.resourceName" placeholder="请输入资源名称" />
          <div class="form-item-tip">资源名称将显示在资源列表中</div>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="resource-uploader"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持各类文档、图片、视频、音频等格式文件，单个文件不超过100MB<br>
                文件将保存在资源库目录下
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-divider content-position="center">高级选项（可选）</el-divider>
        
        <el-form-item label="资源分类" prop="categoryId">
          <el-select v-model="uploadForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
          <div class="form-item-tip">默认为"教学课件"</div>
        </el-form-item>
        
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="uploadForm.resourceType" placeholder="请选择类型">
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
          <div class="form-item-tip">默认为"文档"</div>
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述（可选）"
          />
          <div class="form-item-tip">若不填写，将自动生成描述</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploadLoading">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑资源对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑资源信息"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="resourceName">
          <el-input v-model="editForm.resourceName" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="资源分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="editForm.resourceType" placeholder="请选择类型">
            <el-option v-for="type in resourceTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="editLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资源预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="资源预览"
      width="800px"
    >
      <div class="resource-preview" v-if="currentResource">
        <div class="resource-info">
          <h3>{{ currentResource.resource_name }}</h3>
          <div class="info-item">
            <span class="label">ID:</span>
            <span>{{ currentResource.resource_id }}</span>
          </div>
          <div class="info-item">
            <span class="label">类型:</span>
            <span>{{ currentResource.resource_type }}</span>
          </div>
          <div class="info-item">
            <span class="label">大小:</span>
            <span>{{ formatFileSize(currentResource.file_size) }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间:</span>
            <span>{{ currentResource.create_time }}</span>
          </div>
          <div class="info-item">
            <span class="label">下载次数:</span>
            <span>{{ currentResource.download_count }}</span>
            </div>
          <div class="info-item description">
            <span class="label">描述:</span>
            <div class="description-content">{{ currentResource.description }}</div>
        </div>
      </div>

        <div class="preview-actions">
          <el-button type="primary" @click="handleDownload(currentResource)">
            <el-icon><Download /></el-icon>下载资源
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Download, View, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { resourceAPI } from '@/api/admin/resource'

// 资源列表数据
const resourceList = ref([])
const loading = ref(false)
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 分类列表
const categories = ref([
  { id: 1, name: '教学课件' },
  { id: 2, name: '试题资源' },
  { id: 3, name: '视频资源' },
  { id: 4, name: '图片资源' },
  { id: 5, name: '音频资源' },
  { id: 6, name: '文档资源' },
])

// 资源类型选项
const resourceTypes = [
  { value: 'ppt', label: 'PPT课件' },
  { value: 'doc', label: '文档' },
  { value: 'pdf', label: 'PDF' },
  { value: 'video', label: '视频' },
  { value: 'audio', label: '音频' },
  { value: 'image', label: '图片' },
  { value: 'code', label: '代码' },
  { value: 'other', label: '其他' }
]

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  categoryId: null,
  sortBy: '',
  sortOrder: ''
})

// 上传对话框相关
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploadLoading = ref(false)
const uploadForm = reactive({
  resourceName: '',
  categoryId: null,
  resourceType: '',
  description: '',
  file: null
})

// 表单验证规则
const uploadRules = {
  resourceName: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    { max: 100, message: '资源名称不能超过100个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: false, message: '请选择资源分类', trigger: 'change' }
  ],
  resourceType: [
    { required: false, message: '请选择资源类型', trigger: 'change' }
  ],
  description: [
    { required: false },
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ]
}

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editLoading = ref(false)
const editForm = reactive({
  resourceId: null,
  resourceName: '',
  categoryId: null,
  resourceType: '',
  description: ''
})

// 预览对话框相关
const previewDialogVisible = ref(false)
const currentResource = ref(null)

// 初始化数据
onMounted(() => {
  fetchResourceList()
  fetchCategories()
})

// 获取资源列表
const fetchResourceList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      resource_name: searchForm.name || undefined,
      resource_type: searchForm.type || undefined,
      category_id: searchForm.categoryId || undefined,
      sort_by: searchForm.sortBy || undefined,
      sort_order: searchForm.sortOrder || undefined
    }
    
    // 调用API获取数据
    const res = await resourceAPI.getResourceList(params)
    
    if (res && res.data) {
      resourceList.value = res.data.items || res.data
      pagination.total = res.data.total || res.data.length
      console.log('加载资源列表成功:', resourceList.value)
    } else {
      // 如果API返回失败，使用模拟数据
      console.warn('API返回数据格式不正确，使用模拟数据')
      const mockData = generateMockData()
      resourceList.value = mockData.items
      pagination.total = mockData.total
    }
  } catch (error) {
    console.error('获取资源列表失败:', error)
    ElMessage.error('获取资源列表失败，使用模拟数据')
    
    // 出错时使用模拟数据
    const mockData = generateMockData()
    resourceList.value = mockData.items
    pagination.total = mockData.total
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    // 调用API获取分类
    const res = await resourceAPI.getResourceCategories()
    
    if (res && res.data) {
      categories.value = res.data
      console.log('获取分类列表成功:', categories.value)
    } else {
      // 如果API返回失败，使用默认分类
      console.warn('API返回数据格式不正确，使用默认分类')
      categories.value = [
        { id: 1, name: '教学课件' },
        { id: 2, name: '试题资源' },
        { id: 3, name: '视频资源' },
        { id: 4, name: '图片资源' },
        { id: 5, name: '音频资源' },
        { id: 6, name: '文档资源' }
      ]
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 出错时使用默认分类
    categories.value = [
      { id: 1, name: '教学课件' },
      { id: 2, name: '试题资源' },
      { id: 3, name: '视频资源' },
      { id: 4, name: '图片资源' },
      { id: 5, name: '音频资源' },
      { id: 6, name: '文档资源' }
    ]
  }
}

// 刷新数据
const refreshData = () => {
  fetchResourceList()
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchResourceList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'sortBy' || key === 'sortOrder' ? '' : null
  })
  pagination.currentPage = 1
  fetchResourceList()
}

// 排序变化处理
const handleSortChange = ({ prop, order }) => {
  if (prop && order) {
    searchForm.sortBy = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  } else {
    searchForm.sortBy = ''
    searchForm.sortOrder = ''
  }
  fetchResourceList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchResourceList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchResourceList()
}

// 打开上传对话框
const openUploadDialog = () => {
  uploadForm.resourceName = ''
  uploadForm.categoryId = 1 // 默认分类ID为1
  uploadForm.resourceType = 'document' // 默认类型为document
  uploadForm.description = ''
  uploadForm.file = null
  
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  uploadDialogVisible.value = true
}

// 文件变化处理
const handleFileChange = (file) => {
  uploadForm.file = file.raw
}

// 文件移除处理
const handleFileRemove = () => {
  uploadForm.file = null
}

// 取消上传
const cancelUpload = () => {
  uploadDialogVisible.value = false
}

// 提交上传
const submitUpload = async () => {
  if (!uploadForm.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  uploadFormRef.value.validate(async (valid) => {
    if (valid) {
      uploadLoading.value = true
      try {
        // 创建FormData对象，用于文件上传
        const formData = new FormData()
        formData.append('file', uploadForm.file)
        formData.append('resource_name', uploadForm.resourceName)
        formData.append('category_id', uploadForm.categoryId || 1) // 默认分类ID为1
        formData.append('resource_type', uploadForm.resourceType || 'document') // 默认类型为document
        
        if (uploadForm.description) {
          formData.append('description', uploadForm.description)
        } else {
          formData.append('description', `通过API上传的${uploadForm.resourceType || 'document'}类型资源`)
        }
        
        console.log('上传资源数据:', Object.fromEntries(formData))
        
        // 调用API上传文件
        const res = await resourceAPI.uploadResourceFile(formData)
        
        console.log('上传响应:', res)
        
        if (res.status === 'success' || res.code === 200 || res.data) {
          ElMessage.success(res.message || '资源上传成功')
          uploadDialogVisible.value = false
          fetchResourceList() // 刷新列表
        } else {
          throw new Error(res.message || '上传失败')
        }
      } catch (error) {
        console.error('上传资源失败:', error)
        ElMessage.error('上传资源失败：' + (error.message || '未知错误'))
      } finally {
        uploadLoading.value = false
      }
    }
  })
}

// 预览资源
const handlePreview = (row) => {
  currentResource.value = row
  previewDialogVisible.value = true
}

// 下载资源
const handleDownload = (row) => {
  try {
    // 获取下载链接
    const downloadUrl = resourceAPI.getDownloadUrl(row.resource_id)
    
    // 创建一个隐藏的<a>元素用于下载
    const link = document.createElement('a')
    link.href = downloadUrl
    link.target = '_blank'
    link.download = row.resource_name // 设置下载文件名
    
    // 模拟点击
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success(`开始下载资源：${row.resource_name}`)
  } catch (error) {
    console.error('下载资源失败:', error)
    ElMessage.error('下载资源失败，请重试')
  }
}

// 编辑资源
const handleEdit = (row) => {
  editForm.resourceId = row.resource_id
  editForm.resourceName = row.resource_name
  editForm.categoryId = row.category_id
  editForm.resourceType = row.resource_type
  editForm.description = row.description || ''
  
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        const data = {
          resource_name: editForm.resourceName,
          category_id: editForm.categoryId,
          resource_type: editForm.resourceType,
          description: editForm.description
        }
        
        // 调用API更新资源
        const res = await resourceAPI.updateResource(editForm.resourceId, data)
        
        if (res.status === 'success' || res.code === 200 || res.data) {
          ElMessage.success('资源信息更新成功')
          editDialogVisible.value = false
          fetchResourceList() // 刷新列表
        } else {
          throw new Error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新资源失败:', error)
        ElMessage.error('更新资源失败：' + (error.message || '未知错误'))
      } finally {
        editLoading.value = false
      }
    }
  })
}

// 删除资源
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除资源 "${row.resource_name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用API删除资源
      const res = await resourceAPI.deleteResource(row.resource_id)
      
      if (res.status === 'success' || res.code === 200 || res.data) {
        ElMessage.success('资源删除成功')
        fetchResourceList() // 刷新列表
      } else {
        throw new Error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除资源失败:', error)
      ElMessage.error('删除资源失败：' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    0: 'info',    // 待审核
    1: 'success', // 审核通过
    2: 'danger',  // 审核驳回
    3: 'warning'  // 已下架
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '待审核',
    1: '已发布',
    2: '已驳回',
    3: '已下架'
  }
  return map[status] || '未知状态'
}

// 获取资源类型标签样式
const getTypeTagType = (type) => {
  const map = {
    'ppt': '',
    'doc': 'success',
    'pdf': 'danger',
    'video': 'warning',
    'audio': 'info',
    'image': 'success',
    'code': 'warning',
    'other': 'info'
  }
  return map[type] || ''
}

// 生成模拟数据方法 (实际项目中删除此方法)
const generateMockData = () => {
  // 固定资源列表，包含用户提供的两条记录
  const fixedItems = [
    {
      resource_id: 5,
      resource_name: "ai_teach教师表20250410023149.docx",
      category_id: 1,
      category_name: '教学课件',
      resource_type: "document",
      file_path: "H:\\毕业设计\\ai_teach\\..\\resource_files\\ai_teach教师表20250410023149.docx",
      file_size: 11139,
      description: "通过API上传的document类型资源",
      audit_status: 0,
      audit_opinion: null,
      download_count: 0,
      create_time: "2025-05-10 21:15:56",
      update_time: "2025-05-10 21:15:56",
      status: 1,
      creator_id: 0
    },
    {
      resource_id: 8,
      resource_name: "《基于生成式人工智能的教学管理平台的分析设计——管理端子系统》初稿.pdf",
      category_id: 1,
      category_name: '教学课件',
      resource_type: "document",
      file_path: "H:\\毕业设计\\ai_teach\\..\\resource_files\\《基于生成式人工智能的教学管理平台的分析设计——管理端子系统》初稿.pdf",
      file_size: 2923379,
      description: "通过API上传的document类型资源",
      audit_status: 0,
      audit_opinion: null,
      download_count: 0,
      create_time: "2025-05-10 21:54:01",
      update_time: "2025-05-10 21:54:01",
      status: 1,
      creator_id: 0
    }
  ];
  
  // 生成其他随机资源
  const randomItems = [];
  const baseTime = new Date();
  
  for (let i = 1; i <= 10; i++) {
    const id = i + 10; // 避免ID冲突
    const createdDate = new Date(baseTime);
    createdDate.setDate(baseTime.getDate() - Math.floor(Math.random() * 30));
    
    const fileSize = Math.floor(Math.random() * 100000000); // 随机生成文件大小(B)
    const categoryId = Math.floor(Math.random() * 6) + 1;
    const categoryMap = {
      1: '教学课件',
      2: '试题资源',
      3: '视频资源',
      4: '图片资源',
      5: '音频资源',
      6: '文档资源'
    };
    
    const types = ['ppt', 'doc', 'pdf', 'video', 'audio', 'image', 'code', 'other'];
    const resourceType = types[Math.floor(Math.random() * types.length)];
    
    randomItems.push({
      resource_id: id,
      resource_name: `示例资源${id}`,
      category_id: categoryId,
      category_name: categoryMap[categoryId],
      resource_type: resourceType,
      file_path: `/resource_files/example${id}.${resourceType}`,
      file_size: fileSize,
      description: `这是一个示例资源${id}，用于演示资源管理功能。`,
      audit_status: Math.floor(Math.random() * 4),
      audit_opinion: null,
      download_count: Math.floor(Math.random() * 100),
      create_time: createdDate.toISOString().split('T')[0],
      update_time: new Date().toISOString().split('T')[0],
      status: 1,
      creator_id: 1
    });
  }
  
  // 合并固定和随机资源
  const allItems = [...fixedItems, ...randomItems];
  
  // 根据搜索条件筛选
  let filteredItems = allItems;
  if (searchForm.name) {
    filteredItems = filteredItems.filter(item => 
      item.resource_name.toLowerCase().includes(searchForm.name.toLowerCase())
    );
  }
  if (searchForm.type) {
    filteredItems = filteredItems.filter(item => 
      item.resource_type === searchForm.type
    );
  }
  if (searchForm.categoryId) {
    filteredItems = filteredItems.filter(item => 
      item.category_id === searchForm.categoryId
    );
  }
  
  // 排序
  if (searchForm.sortBy) {
    filteredItems.sort((a, b) => {
      const valueA = a[searchForm.sortBy];
      const valueB = b[searchForm.sortBy];
      const direction = searchForm.sortOrder === 'asc' ? 1 : -1;
      
      if (typeof valueA === 'string') {
        return direction * valueA.localeCompare(valueB);
      } else {
        return direction * (valueA - valueB);
      }
    });
  }
  
  // 分页
  const total = filteredItems.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  const paginatedItems = filteredItems.slice(start, end);
  
  return {
    items: paginatedItems,
    total: total
  };
}
</script>

<style scoped>
.resource-management-container { padding: 24px; }
.header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.resource-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.resource-table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.resource-name {
  cursor: pointer;
  color: #409eff;
}

.resource-uploader {
  width: 100%;
}

.resource-preview {
  padding: 20px;
}

.resource-info {
  margin-bottom: 20px;
}

.resource-info h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.info-item .label {
  width: 100px;
  font-weight: bold;
}

.description {
  align-items: flex-start;
}

.description-content {
  flex: 1;
  white-space: pre-wrap;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-item-tip {
  font-size: 0.8em;
  color: #909399;
  margin-top: 5px;
}
</style> 